package com.uxsino.simo.indicator.retractor;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.uxsino.commons.utils.config.ConfigProp;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @ClassName OracleRacRetractor
 * @Description TODO
 * @Author Liuxh
 * @Date 2020/4/16 14:15
 * @Version 1.0
 */
public class OracleRacRetractor extends ListValueRetractor{

	Logger logger = LoggerFactory.getLogger(OracleRacRetractor.class);
	@ConfigProp(name = "column_delimeter", trim = false)
	public String columnDelimeter;
	@ConfigProp(name = "row_delimeter", trim = false)
	public String rowDelimeter;
	protected Map<String, Integer> columnNames;
	public OracleRacRetractor() {
		columnNames = new HashMap<>();
		rowDelimeter = "\n\n";
	}
	@Override
	public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
		String string = (String)obj;
		List<Map<String, Object>> data  = Lists.newArrayList();
		//行
		String[] lines = getLines(string);
		for (String line : lines) {
			String[] rec = splitRow(line);
			if (rec == null) {
				continue;
			}
			HashMap<String, Object> fieldValues = new HashMap<String, Object>();

			for (ColumnEntry entry : columnEntries) {
				Object value = null;
				String field = getFieldString(entry.index, rec);
				if (!StringUtils.isEmpty(field)) {
					value = entry.retractor.retract(entity, ctxt, qt, field);
					String[] kv = value.toString().split("=");
					fieldValues.put(entry.field.getName(), Strings.nullToEmpty(kv[1]).replaceAll("\\s+", " "));
				} else {
					logger.info("field isEmpty");
				}

			}
			if (!fieldValues.isEmpty()) {
				data.add(fieldValues);
			}
		}
		return data;
	}

	//行
	protected String[] getLines(String s) {
		return s.split(rowDelimeter);
	}
	protected String[] splitRow(String row) {
		String[] r = row.split("\n");
		return r;
	}
	protected String getFieldString(String index, String[] record) {
		if(Strings.isNullOrEmpty(index)){
			return null;
		}
		int i = columnNames.getOrDefault(index, -1);
		if (i == -1) {
			try {
				i = Integer.parseInt(index);
			} catch (NumberFormatException e) {
				logger.error("parse " + index, e);
			}
		}
		if (i < 1 || i > record.length) {
			return null;
		}

		return record[i - 1];
	}
}
